<template>
    <a-modal :keyboard="false" :maskClosable="false" title="人员选择" :open="visible" :width="1100" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <div class="flex left-right-wrap org-modal-body">
            <div class="left-wrap">
                <a-tree
                    :height="320"
                    v-model:expandedKeys="expandedKeys"
                    v-model:selectedKeys="selectedKeys"
                    :field-names="fieldNames"
                    :tree-data="treeData"
                    @select="handleTreeSelect"
                ></a-tree>
            </div>
            <div class="right-wrap">
                <a-row :gutter="16" type="flex" justify="start">
                    <a-col :xs="12" :sm="12" :md="8">
                        <a-form layout="horizontal">
                            <a-form-item>
                                <a-input placeholder="姓名/手机号" v-model:value="queryParams.keyword" allow-clear />
                            </a-form-item>
                        </a-form>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8">
                        <a-button @click="handleSearch" type="primary">搜索</a-button>
                        <a-button @click="handleReset" class="ml-5px">重置</a-button>
                    </a-col>
                </a-row>
                <a-table
                    row-key="code"
                    :size="state.tableSize"
                    :loading="state.loading"
                    :columns="dynamicColumns"
                    :data-source="state.dataSource"
                    :pagination="{
                        'show-size-changer': true,
                        current: state.current,
                        pageSize: state.pageSize,
                        total: state.total,
                        showTotal: total => `共 ${total} 条`,
                    }"
                    :row-selection="{ type: 'radio', selectedRowKeys: tableSelectedRowKeys, onChange: handleTableSelectChange }"
                    :scroll="{ y: 300 }"
                    @change="handleTableChange"
                >
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'org'">
                            <a-tooltip :content="[record.corpName, record.deptName, record.jobName].filter(Boolean).join('/')">
                                {{ [record.corpName, record.deptName, record.jobName].filter(Boolean).join('/') }}
                            </a-tooltip>
                        </template>
                    </template>
                </a-table>
            </div>
        </div>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType, Ref } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form } from 'ant-design-vue';
    import { cloneDeep, isEmpty } from 'lodash-es';
    import type { TreeProps } from 'ant-design-vue';
    import { queryYfOrgTree, usersByOrg, queryOrgTree } from '@/api/common/mdm';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import type { Pagination, TableColumn } from '@/typing';

    type Key = string | number;

    const baseColumns: TableColumn[] = [
        {
            title: '姓名',
            dataIndex: 'name',
            width: 100,
        },
        {
            title: '联系电话',
            dataIndex: 'workPhone',
            width: 150,
        },
        {
            title: '条线',
            dataIndex: 'professionalLine',
            customRender: ({ text }) => (text ? text.replace('品质', '') : ''),
            width: 150,
        },
        {
            title: '公司岗位',
            dataIndex: 'org',
            ellipsis: true,
        },
    ];

    const fieldNames: TreeProps['fieldNames'] = {
        children: 'children',
        title: 'name',
        key: 'code',
    };

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'confirm'],
        setup(props, { emit }) {
            const loading = ref(false);
            const treeData: Ref<TreeProps['treeData']> = ref([]);
            const expandedKeys = ref<string[]>([]);
            const selectedKeys = ref<string[]>([]);
            const tableSelectedRowKeys = ref<Key[]>([]);
            const queryParams = reactive<any>({
                keyword: '',
            });
            const fetchDataContext = reactive<any>({
                current: 1,
                pageSize: 10,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: true,
                executeImmediately: false,
                requestParams: { ...queryParams },
            });
            const { state: columnState, dynamicColumns, dynamicColumnItems } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
            const modelRef = reactive<any>({
                status: 1,
                projectCodes: [],
            });
            const rulesRef = reactive({
                code: [{ required: true, message: '请选择员工' }],
                roleIds: [{ required: true, message: '请选择角色' }],
                projectCodes: [{ required: true, message: '请设置负责项目' }],
            });
            const { validateInfos, resetFields } = Form.useForm(modelRef, rulesRef);
            // 表格数据和加载
            const { reload, context: state } = useFetchData(usersByOrg, fetchDataContext);

            const handleTableChange = ({ current, pageSize }: Pagination) => {
                // filteredInfoMap.value = filters;
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    (props.model.treeType !== 'wy' ? queryYfOrgTree : queryOrgTree)().then(res => {
                        if (!isEmpty(res.data)) {
                            treeData.value = [res.data as any];
                            expandedKeys.value = [res.data.code];
                            selectedKeys.value = [res.data.code];

                            fetchDataContext.requestParams.orgCode = res.data.code;

                            handleTreeSelect([res.data.code]);
                        }
                    });
                    if (props.model) {
                        Object.assign(modelRef, props.model);
                    }
                }
            });

            const handleTreeSelect = checkedKeys => {
                console.log(checkedKeys);

                selectedKeys.value = checkedKeys;

                queryParams.orgCode = checkedKeys.join(',');
                fetchDataContext.executeImmediately = true;

                // handleTableChange({
                //     current: 1,
                //     pageSize: 15,
                // });
                handleSearch();
            };

            const handleTableSelectChange = (selectedRowKeys: Key[]) => {
                tableSelectedRowKeys.value = selectedRowKeys;
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.keys(queryParams).forEach(key => {
                    delete queryParams[key];
                });

                modelRef.projectCodes = [];
                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                if (!isEmpty(tableSelectedRowKeys.value)) {
                    const user = state.dataSource.find(item => tableSelectedRowKeys.value.includes(item.code));
                    emit('confirm', user);
                    tableSelectedRowKeys.value = [];
                }
                handleCancel();
            };

            const handleSearch = () => {
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...queryParams };
            };
            const handleReset = () => {
                queryParams.keyword = '';
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...queryParams };
            };
            return {
                loading,

                reload,
                state,
                columnState,
                dynamicColumns,
                dynamicColumnItems,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,

                treeData,
                fieldNames,
                expandedKeys,
                selectedKeys,
                tableSelectedRowKeys,

                handleTreeSelect,

                handleTableChange,

                handleTableSelectChange,
                handleSearch,
                handleReset,
                queryParams,
            };
        },
    });
</script>

<style lang="less" scoped>
    .org-modal-body {
        height: 450px;
        width: 100%;
        .left-wrap,
        .right-wrap {
            height: 100%;
        }
    }
</style>
